package com.haohan.cloud.scm.manage.core.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.haohan.cloud.scm.api.common.entity.resp.UploadPhotoResp;
import com.haohan.cloud.scm.api.constant.enums.manage.PhotoTypeEnum;
import com.haohan.cloud.scm.api.manage.dto.PhotoGroupDTO;
import com.haohan.cloud.scm.api.manage.entity.PhotoGallery;
import com.haohan.cloud.scm.api.manage.entity.PhotoGroupManage;
import com.haohan.cloud.scm.api.manage.entity.PhotoManage;
import com.haohan.cloud.scm.api.manage.trans.PhotoTrans;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.common.tools.util.AliyunOssUtils;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.haohan.cloud.scm.manage.core.PhotoManageCoreService;
import com.haohan.cloud.scm.manage.service.PhotoGalleryService;
import com.haohan.cloud.scm.manage.service.PhotoGroupManageService;
import com.haohan.cloud.scm.manage.service.PhotoManageService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.data.tenant.TenantContextHolder;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author dy
 * @date 2019/9/11
 */
@Service
@AllArgsConstructor
public class PhotoManageCoreServiceImpl implements PhotoManageCoreService {

    private final PhotoGalleryService photoGalleryService;
    private final PhotoManageService photoManageService;
    private final PhotoGroupManageService photoGroupManageService;

    /**
     * 查询图片组图片信息
     *
     * @param groupNum
     * @return
     */
    @Override
    public PhotoGroupDTO fetchByGroupNum(String groupNum) {
        PhotoGroupManage photoGroupManage = photoGroupManageService.getByGroupNum(groupNum);
        if (null == photoGroupManage) {
            return null;
        }
        PhotoGroupDTO photoGroupDTO = new PhotoGroupDTO();
        BeanUtil.copyProperties(photoGroupManage, photoGroupDTO);
        List<PhotoManage> photoManageList = photoManageService.findListByNum(groupNum);
        List<PhotoGallery> photoList = new ArrayList<>();
        // 防止图片重复
        Set<String> galleryIdSet = new HashSet<>(Math.max(8, photoManageList.size() * 4 / 3 + 1));
        for (PhotoManage manage : photoManageList) {
            String galleryId = manage.getPhotoGalleryId();
            if (!galleryIdSet.contains(galleryId)) {
                PhotoGallery photo = new PhotoGallery();
                photo.setId(galleryId);
                photo.setPicUrl(manage.getPicUrl());
                photoList.add(photo);
                galleryIdSet.add(galleryId);
            }
        }
        photoGroupDTO.setPhotoList(photoList);
        return photoGroupDTO;
    }

    /**
     * 新增图片组图片
     *
     * @param group photoList 中需有photoGalleryId
     * @return
     */
    @Override
    public PhotoGroupManage addPhotoGroup(PhotoGroupDTO group) {
        // 验证图片资源id 并获取
        List<PhotoGallery> photoGalleryList = fetchPhotoList(transToIdSet(group.getPhotoList()));
        if (CollUtil.isEmpty(photoGalleryList)) {
            return null;
        }
        // 新增图片组
        PhotoGroupManage photoGroupManage = new PhotoGroupManage();
        photoGroupManage.setMerchantId(group.getMerchantId());
        photoGroupManage.setGroupName(group.getGroupName());
        photoGroupManage.setCategoryTag(group.getCategoryTag());
        photoGroupManageService.save(photoGroupManage);
        String groupNum = photoGroupManage.getGroupNum();
        // 新增图片管理
        for (PhotoGallery photo : photoGalleryList) {
            photoManageService.addPhotoManage(groupNum, photo);
        }
        return photoGroupManage;
    }

    private Set<String> transToIdSet(List<PhotoGallery> list) {
        return list.stream()
                .map(PhotoGallery::getId)
                .collect(Collectors.toSet());
    }

    /**
     * 图片组修改图片
     *
     * @param group photoList 中需有photoGalleryId
     * @return
     */
    @Override
    public void modifyPhotoGroup(PhotoGroupDTO group) {
        String groupNum = group.getGroupNum();
        Set<String> idSet = transToIdSet(group.getPhotoList());
        // 验证图片资源id 并获取
        List<PhotoGallery> photoGalleryList = fetchPhotoList(idSet);
        // 查询原有 图片管理
        List<PhotoManage> photoManageList = photoManageService.findListByNum(groupNum);
        Set<String> deleteManageIdSet = new HashSet<>(Math.max(8, photoManageList.size() * 4 / 3 + 1));
        for (PhotoManage manage : photoManageList) {
            String galleryId = manage.getPhotoGalleryId();
            if (idSet.contains(galleryId)) {
                idSet.remove(manage.getPhotoGalleryId());
            } else {
                deleteManageIdSet.add(manage.getId());
            }
        }
        // 筛选 新增和删除的 图片管理
        for (PhotoGallery photo : photoGalleryList) {
            if (idSet.contains(photo.getId())) {
                photoManageService.addPhotoManage(groupNum, photo);
            }
        }
        // 删除
        for (String manageId : deleteManageIdSet) {
            photoManageService.removeById(manageId);
        }
    }

    private List<PhotoGallery> fetchPhotoList(Set<String> galleryIdSet) {
        List<PhotoGallery> photoGalleryList = new ArrayList<>();
        PhotoGallery photoGallery;
        for (String galleryId : galleryIdSet) {
            photoGallery = photoGalleryService.getById(galleryId);
            if (null != photoGallery) {
                photoGalleryList.add(photoGallery);
            }
        }
        return photoGalleryList;
    }

    /**
     * 修改时：需groupNum / photoList
     * 新增时 需 图片组名称/ 类别标签 / merchantId
     *
     * @param photoGroupDTO
     * @return 无图片列表时返回null
     */
    @Override
    public PhotoGroupManage editPhotoGroup(PhotoGroupDTO photoGroupDTO) {
        PhotoGroupManage photoGroupManage;
        if (StrUtil.isBlank(photoGroupDTO.getGroupNum())) {
            photoGroupManage = null;
        } else {
            photoGroupManage = photoGroupManageService.getByGroupNum(photoGroupDTO.getGroupNum());
        }
        // 已有图片组修改
        if (null == photoGroupManage) {
            photoGroupManage = addPhotoGroup(photoGroupDTO);
        } else {
            modifyPhotoGroup(photoGroupDTO);
        }
        return photoGroupManage;
    }

    /**
     * 图片上传
     *
     * @param file
     * @param type
     * @param suffix
     * @return
     */
    @Override
    public UploadPhotoResp uploadPhoto(MultipartFile file, PhotoTypeEnum type, String suffix) {
        // 文件名处理 时间戳
        String objectName = AliyunOssUtils.fetchFilePath(String.valueOf(TenantContextHolder.getTenantId()), type.getType())
                + AliyunOssUtils.fetchFileName(suffix);
        // 上传阿里云
        R<String> upload = AliyunOssUtils.uploadFile(file, objectName);
        if (RUtil.isFailed(upload)) {
            throw new ErrorDataException(upload.getMsg());
        }
        String url = upload.getData();
        // 保存
        PhotoGallery photo = PhotoTrans.initPhotoUpload(file, url, type);
        photoGalleryService.save(photo);
        UploadPhotoResp resp = new UploadPhotoResp();
        resp.setPhotoGalleryId(photo.getId());
        resp.setPhotoUrl(url);
        return resp;
    }


}
